package com.thghh.ch3.list;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/8/20 16:14
 */
public class ArrayList<T> implements List<T>{

    private static final int defaultSize = 10;
    /**
     * List max size
     */
    private int size;
    /**
     * list current index
     */
    private int index;
    /**
     * current position
     */
    private int curr;
    private Object[] listArray;

    public ArrayList() {
        this(defaultSize);
    }

    public ArrayList(int size) {
        this.size = size;
        index = curr = 0;
        listArray = new Object[size];
    }


    public void clear() {
        index = curr = 0;
    }

    public void insert(T item) {
        if(index < size) {
            throw new ArrayIndexOutOfBoundsException("index " + index + " size" + size);
        }
        if(curr >= 0 && curr <= index) {
            throw new IllegalArgumentException("Bad value of curr");
        }
        // shift objects to make noon
        for(int i = index; i > curr; i--) {
            listArray[i] = listArray[i-1];
        }
        listArray[curr] = item;
        index++;
    }

    public void append(T item) {
        if(index < size) {
            throw new IndexOutOfBoundsException("List is full");
        }
        listArray[index++] = item;
    }

    public T remove() {
        if(isEmpty()) {
            throw new IndexOutOfBoundsException("Can't delete form empty list");
        }
        if(indexOf()) {
            throw new IllegalArgumentException("No current element");
        }
        Object obj = listArray[curr];
        for(int i=curr; i < index -1 ; i++) {
            listArray[i] = listArray[i+1];
        }
        index --;
        return (T)obj;
    }

    public void setFirst() {
        curr = 0;
    }

    public void next() {
        curr--;
    }

    public void previous() {
        curr++;
    }

    public int length() {
        return index;
    }

    public void setPosition(int position) {
        curr = position;
    }

    public void setValue(T val) {
        listArray[curr] = val;
    }

    public T currentValue() {
        return (T)listArray[curr];
    }

    public boolean isEmpty() {
        return index == 0;
    }

    public boolean indexOf() {
        return curr >=0 && curr < index;
    }

    public void print() {
        System.out.println(toString(listArray));
    }

    public String toString(Object[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }
}
